package com.fingard.dsp.bank.directbank.yzb01;

import java.io.File;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import static com.fingard.io.FileHelper.*;
import static com.fingard.text.StringHelper.trimEndFileSp;

public class YZB01BatPayRec extends YZB01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts =  new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.writeStart();

        String filePath  = getBankConfig().getValueAsString("IDTransformDirectory");
        if(!existFile(filePath)){
            mkdir(filePath);
        }

        String PostScriptPath = getBankConfig().getValueAsString("PostScriptPath");
        if(!existFile(PostScriptPath)){
            mkdir(PostScriptPath);
        }

        XmlTextWriter xmlWriter =  new XmlTextWriter();
        YZB01Header header =  new YZB01Header();
        String OpName = "B2EAgentSalaryFileStream";
        header.transCode = OpName;
        header.reqSeqNo = p_req1988.reqHeader.reqSeqID;
        xmlWriter.autoFormat = false;
        writeCommonHead(xmlWriter,header);

        XElement tmpXElement = new XElement("Body", "");
        tmpXElement.addChild(new XElement("PayerAcNo",p_req1988.ownAct));
        //代发不支持外币
        String Currency = convertCurToBank(p_req1988.ownCur);
        tmpXElement.addChild(new XElement("Currency",Currency));
        tmpXElement.addChild(new XElement("Amount",p_req1988.totalAmt));
        tmpXElement.addChild(new XElement("TotalCount",p_req1988.totalNum));
        StringBuilder content = new StringBuilder();
        StringBuilder PostScriptContent  = new StringBuilder();
        while(p_req1988.readRecord()){
            content.append(p_req1988.readedDetail.recAct + "|" + p_req1988.readedDetail.recName + "|" + p_req1988.readedDetail.payAmount + "|" + p_req1988.readedDetail.abstractATS +"|"+ "\n");
            PostScriptContent.append(p_req1988.readedDetail.abstractATS + "|");
        }
        tmpXElement.addChild(new XElement("UploadFile",content.toString()));

        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();

        String PostScriptName = trimEndFileSp(PostScriptPath) + File.separator + p_req1988.reqBatchNO + "_postScript";
        WriteBankLogLn("写入批付映射码位置：" + PostScriptName);
        WriteBankLogLn("写入批付文件内容："+ PostScriptContent.toString());
        writeFile(PostScriptName,PostScriptContent.toString(),"GBK");

        String[] retStrArr = sendToBank(xmlWriter.toXmlString(),OpName);
        if(retStrArr[0].length() == 0){
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            retAts.reqSeqID = p_req1988.reqBatchNO;
            if(tmpBkReader != null){
                String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/OpRetCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/OpRetMsg");
                if("0000".equals(tmpRetCode)){
                    retAts.respCode = "0";
                    retAts.respInfo = tmpRetInfo;
                    retAts.transState = tmpRetCode ;
                    retAts.payInfoCode  = tmpRetCode;

                    String FullName =  trimEndFileSp(filePath)  + File.separator + p_req1988.reqBatchNO + "_askNumber";
                    String FileContent = tmpBkReader.getSimpleText("BatchNo");
                    WriteBankLogLn("写入文件位置：" + FullName);
                    WriteBankLogLn("写入文件内容：" +  tmpBkReader.getSimpleText("BatchNo"));
                    writeFile(FullName,FileContent,"GBK");
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        }
        else{
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1].toString());
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    //不需要分页
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts  = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.writeStart();

        String FilePath =  getBankConfig().getValueAsString("IDTransformDirectory");
        String BatRecord = "";
        if(!existFile(FilePath)){
            BatRecord = getBatRecord(p_req1998);
            if(StringHelper.isNullOrEmpty(BatRecord)) {
                retAts.respCode = "-1";
                retAts.respInfo = "不存在对应的请求序列号或对应交易失败,请检查对应文件夹";
                retAts.writeEnd();
                return retAts;
            }
            else if(BatRecord.equals("1")){
                retAts.respCode = "0";
                retAts.transState = "E1311";
                retAts.payInfoCode = "E1311";
                retAts.respInfo = "对应记录为空";
                retAts.writeEnd();
                return retAts;
            }
        }
        String PostScriptPath  = getBankConfig().getValueAsString("PostScriptPath");
        if(!existFile(PostScriptPath)){
            retAts.respCode = "-1";
            retAts.respInfo = "不存在对应的对账码,请检查对应文件夹";
            retAts.writeEnd();
            return retAts;
        }

        String fullName  = FilePath  + File.separator + p_req1998.reqBatchNO + "_askNumber";
        WriteBankLogLn("读取文件位置：" + fullName);
        String askNumber;
        if(!existFile(fullName)){
            WriteBankLogLn("文件不存在，取银行返回对应批次号");
            askNumber =BatRecord;
        }
        else
        {
            askNumber = readFileText(fullName,"GBK");
        }
        WriteBankLogLn("读取文件内容:" + askNumber);

        String PostScriptName = PostScriptPath + File.separator + p_req1998.reqBatchNO + "_postScript";
        WriteBankLogLn("读取对账码文件位置：" + PostScriptName);
        String PostScriptContent = readFileText(PostScriptName,"GBK");
        WriteBankLogLn("读取对账码文件内容" + PostScriptContent);

        String[] PostScripts  = PostScriptContent.split("\\|");

        XmlTextWriter xmlWriter =  new XmlTextWriter();
        YZB01Header header =  new YZB01Header();
        String OpName = "B2EAgentSalaryQueryStream";
        header.transCode = OpName;
        header.reqSeqNo = p_req1998.reqHeader.reqSeqID;
        xmlWriter.autoFormat = false;
        writeCommonHead(xmlWriter,header);

        XElement tmpElement =  new XElement("Body","");
        tmpElement.addChild(new XElement("TransDate",  Format.Date8Format.format(p_req1998.getBgnDateTime())));
        tmpElement.addChild(new XElement("BatchNo",askNumber));

        xmlWriter.writeXElement(tmpElement);
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString(),OpName);
        if(retStrArr[0].length() == 0){
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if(tmpBkReader != null){
                String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/OpRetCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/OpRetMsg");
                if("0000".equals(tmpRetCode)){
                    retAts.respCode = "0";
                    String AllDetail =  tmpBkReader.getSimpleText("FileContent");
                    String[] details =  AllDetail.split("\n");
                    for (int i = 0 ; i < details.length ; i++){
                        RetAtsBatPayRecDetail retAtsDetail =  new RetAtsBatPayRecDetail();
                        String[] PayResult = details[i].split("\\|");
                        String AccountNumber =  PayResult[0];
                        String AccountName =  PayResult[1];
                        String Amount = PayResult[2];
                        String Result =  PayResult[3];
                        String PayInfo = PayResult[4];
                        retAtsDetail.result =  tmpRetCode + "+" + Result;
                        retAtsDetail.memo  = PayInfo;
                        retAtsDetail.payInfoCode =  tmpRetCode + "+" + Result;
                        retAtsDetail.recAct = AccountNumber;
                        retAtsDetail.recName = AccountName;
                        retAtsDetail.payAmount = Amount;
                        retAtsDetail.postScript  = PostScripts[i];  //银行返回对账码没有埋入，需从文件中映射
                        retAts.writeRetDetail(retAtsDetail);
                    }
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        }
        else{
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1].toString());
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    public String getBatRecord(ReqQryBatPayRec p_req1998) throws  Exception {
        String retStr = "";
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.writeStart();
        XmlTextWriter xmlWriter = new XmlTextWriter();
        YZB01Header header = new YZB01Header();
        String OpName = "B2EAgentSalaryListQuery";
        header.transCode = OpName;
        header.reqSeqNo = p_req1998.reqHeader.reqSeqID;
        xmlWriter.autoFormat = false;
        writeCommonHead(xmlWriter, header);

        XElement tmpElement = new XElement("Body", "");
        tmpElement.addChild(new XElement("EntJnlNo", p_req1998.reqBatchNO));
        tmpElement.addChild(new XElement("BeginDate", ""));
        tmpElement.addChild(new XElement("EndDate", ""));
        tmpElement.addChild(new XElement("pageSize", ""));
        tmpElement.addChild(new XElement("currentIndex", "0"));

        xmlWriter.writeXElement(tmpElement);
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString(), OpName);

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/OpRetCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/OpRetMsg");
                if ("0000".equals(tmpRetCode)) {
                    retStr = tmpBkReader.getFirstText("/Root/Body/List/Record/JnlState");
                    if(retStr.equals("0")){
                        retStr = tmpBkReader.getFirstText("/Root/Body/List/Record/BatchNo");
                    }
                }
            }
        }
        return retStr;
    }
}
